import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { setStorage } from '../lib/utils';
import { message } from 'antd';

const request = axios.create({
  baseURL: '/',
  timeout: 5000,
});

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response: AxiosResponse) => {
    const { status, data } = response;
    if (status === 200) {
      return data.data;
    }

    if (status === 401) {
      setStorage('token', '');
      message.error('登录过期，请重新登录');
      window.location.href = window.location.origin + '/login';
      return Promise.reject(data.message || '登录过期，请重新登录');
    }

    message.error(data.message || '请求失败');
    return Promise.reject(data.message || '请求失败');
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default request;